{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "632d30a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.9809523809523809, 0.8444444444444444)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\n",
    "from sklearn.linear_model import LogisticRegression as LR\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "data = load_iris()\n",
    "x=data.data\n",
    "y=data.target\n",
    "xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.3,random_state=420)\n",
    "std = StandardScaler()\n",
    "#对训练集进行标准化\n",
    "x_train_std = std.fit_transform(xtrain)\n",
    "x_test_std = std.fit_transform(xtest)\n",
    "#在l2范式下，判断C和solver的最优值\n",
    "p = {\n",
    "    \"C\":list(np.linspace(0.05,1,19)),\n",
    "    \"solver\":[\"liblinear\",\"sag\",\"newton-cg\",\"lbfgs\"]\n",
    "}\n",
    "model = LR(penalty=\"l2\",max_iter=10000)\n",
    "GS = GridSearchCV(model,p,cv=5)\n",
    "GS.fit(xtrain,ytrain)\n",
    "#将最优参数重新应用于实例化模型，查看训练集和测试集下的分数\n",
    "model=LR(penalty=\"l2\",\n",
    "   max_iter=10000,\n",
    "   C=GS.best_params_[\"C\"],\n",
    "   solver=GS.best_params_[\"solver\"]\n",
    ")\n",
    "model.fit(x_train_std,ytrain)\n",
    "model.score(x_train_std,ytrain),model.score(x_test_std,ytest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb10aa0d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
